package com.xiu.weixin.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xiu.weixin.pojo.User;
import com.xiu.weixin.util.net.NetUtil;

import net.sf.json.JSONObject;

@Controller
public class GetUserInfoController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(GetUserInfoController.class);

	@RequestMapping("/getUserInfo")
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		// 1、引导用户进入授权页面同意授权，获取code
		String code = request.getParameter("code");
		System.out.println("code:" + code);
		logger.info("code:" + code);
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
		url = url.replace("APPID", "wxd3051a5d4581e8d3").replace("SECRET", "27714cea468c8b61a02817af07dec54b")
				.replace("CODE", code);
		String result = NetUtil.get(url);
		System.out.println(result);
		logger.info(result);
		// 2、通过code换取网页授权access_token（与基础支持中的access_token不同）
		String access_token = JSONObject.fromObject(result).getString("access_token");
		String openid = JSONObject.fromObject(result).getString("openid");
		// 3、如果需要，开发者可以刷新网页授权access_token，避免过期
		// 4、通过网页授权access_token和openid获取用户基本信息（支持UnionID机制）
		url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
		url = url.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
		result = NetUtil.get(url);
		System.out.println("用户信息：" + result);
		logger.info("用户信息：" + result);
		JSONObject obj = JSONObject.fromObject(result);
		User user = (User) JSONObject.toBean(obj, User.class);
		System.out.println(result);
		logger.info(result);
		System.out.println(user);
		logger.info(user + "");
		request.setAttribute("user", user);
		request.getRequestDispatcher("/user.jsp").forward(request, response);
	}

}
